
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>浏览页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
        <script src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
    </head>
    <body class="pear-container">
    
        <!-- 顶部查询表单 -->
        
        
        <!-- 数据表格 -->
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md9">
                <div class="layui-card">
                    <div class="layui-card-body">
                        <table id="data-table" lay-filter="data-table"></table>
                    </div>
                </div>
            </div>

            <div class="layui-col-md3">
                <div class="layui-card">
                    <div class="layui-card-header">地图视图(右击地图添加景点)</div>
<!--                    <button type="button" class="pear-btn pear-btn-primary pear-btn-sm" id="image_content" permission="app.admin.upload.avatar">-->
<!--                        <i class="layui-icon layui-icon-upload"></i>上传自定义图层-->
<!--                    </button>-->
<!--                    <button type="button" class="pear-btn pear-btn-primary pear-btn-sm" id="clear_cover_bg" onclick="clearCoverBG()" permission="app.admin.upload.avatar">-->
<!--                        <i class="layui-icon layui-icon-remove"></i>清除自定义图层-->
<!--                    </button>-->
                    <button type="button" class="pear-btn pear-btn-primary pear-btn-sm" id="marker" permission="app.admin.upload.avatar" style="margin-top:10px;">
                        <i class="layui-icon layui-icon-upload"></i>上传标注点图标
                    </button>
                    <div class="layui-card-body" id="map" style="width: 360px; height: 640px;">

                    </div>
                </div>
            </div>
        </div>


        <!-- 表格行工具栏 -->
        <script type="text/html" id="table-bar">
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.scenicspot.update">编辑</button>
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.scenicspot.delete">删除</button>
        </script>

        <script src="/app/admin/component/layui/layui.js"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        <script src="/app/admin/admin/js/common.js"></script>
        
        <script>

            // 相关常量
            const PRIMARY_KEY = "id";
            const SELECT_API = "/app/admin/scenic-spot/select";
            const UPDATE_API = "/app/admin/scenic-spot/update";
            const DELETE_API = "/app/admin/scenic-spot/delete";
            const INSERT_URL = "/app/admin/scenic-spot/insert";
            const UPDATE_URL = "/app/admin/scenic-spot/update";

            let coverImage = "<?=$area['cover_bg']?>";
            var map = null;
            var imageLatLngBounds = new TMap.LatLngBounds(new TMap.LatLng(<?=$area['range_sw_latitude']?>, <?=$area['range_sw_longitude']?>), new TMap.LatLng(<?=$area['range_ne_latitude']?>, <?=$area['range_ne_longitude']?>));

            var menu = null;
            var position = [];

            var data = {id: 1};

            function initMap() {
                //定义地图中心点坐标
                var center = new TMap.LatLng(39.91826, 116.397933)
                //定义map变量，调用 TMap.Map() 构造函数创建地图
                map = new TMap.Map(document.getElementById('map'), {
                    viewMode:'2D',
                    center: center,//设置地图中心点坐标
                    zoom: 10,   //设置地图缩放级别
                    showControl: false,
                    boundary: imageLatLngBounds,
                    baseMap: {
                        type: 'vector',
                        features: ['base', 'building2d']
                    }
                });

                if (coverImage != '') {
                    initCoverImage()
                }

                map.on('rightclick', function(res) {
                    if (menu != null) {
                        clearMenu()
                    }
                    showMenu(res.latLng.lng, res.latLng.lat);
                })

                addMark()
            }

            function Donut(options) {
                TMap.DOMOverlay.call(this, options);
            }

            Donut.prototype = new TMap.DOMOverlay();

            Donut.prototype.onInit = function(options) {
                this.position = options.position;
            };

            Donut.prototype.onDestroy = function() {
                if (this.onClick) {
                    this.dom.removeEventListener(this.onClick);
                }
            };

            Donut.prototype.createDOM = function() {
                let menu = document.createElement('div');

                menu.appendChild(document.createTextNode('在此坐标添加景点'));
                menu.style.cssText = 'position:absolute;top:0;left:60px;background: #666;color:#fff; width: 120px; text-align:center; border:1px solid #fff;cursor:pointer;'

                // click事件监听
                this.onClick = (res) => {
                    // DOMOverlay继承自EventEmitter，可以使用emit触发事件
                    clearMenu()
                    add(this.position)
                };
                // pc端注册click事件，移动端注册touchend事件
                menu.addEventListener('click', this.onClick);
                return menu;
            };

            // 更新DOM元素，在地图移动/缩放后执行
            Donut.prototype.updateDOM = function() {
                if (!this.map) {
                    return;
                }

                // 经纬度坐标转容器像素坐标
                let pixel = this.map.projectToContainer(this.position);

                // 使饼图中心点对齐经纬度坐标点
                let left = pixel.getX() - this.dom.clientWidth / 2 + 'px';
                let top = pixel.getY() - this.dom.clientHeight / 2 + 'px';
                this.dom.style.transform = `translate(${left}, ${top})`;
            };

            function addMark()
            {
                var marker = new TMap.MultiMarker({
                    map: map,
                    styles: {
                        // 点标记样式
                        marker: new TMap.MarkerStyle({
                            width: 24, // 样式宽
                            height: 24, // 样式高
                            direction: 'top',
                            src: "<?=$area['marker_icon']?>"
                        }),
                    },
                    geometries: [
                        // 点标记数据数组
                        <?php foreach ($markers as $marker) : ?>
                        {
                            // 标记位置(纬度，经度，高度)
                            position: new TMap.LatLng(<?=$marker['position']['lat']?>, <?=$marker['position']['lng']?>),
                            styleId: 'marker',
                            content: "<?=$marker['title']?>",
                            properties: {
                                id: <?=$marker['id']?>
                            }
                        },
                        <?php endforeach ?>
                    ],
                });

                marker.on('click', function(evt) {
                    edit2({
                        data: {
                            id: evt.geometry.properties.id
                        }
                    })
                })
            }

            function clearMenu()
            {
                menu.setMap(null)
            }

            function showMenu(longitude, latitude)
            {
                menu = new Donut({
                    map: map,
                    position: new TMap.LatLng(latitude, longitude)
                })

            }

            function initCoverImage()
            {
                new TMap.ImageGroundLayer({
                    bounds: imageLatLngBounds,
                    src: coverImage, //拟覆盖图片的URL
                    map: map,
                });
            }

            function clearCoverBG()
            {
                data.cover_bg = '';
                editArea(true)
            }

            let $ = layui.$;

            $(function() {
               initMap()
            });

            layui.upload.render({
                elem: "#image_content",
                url: "/app/admin/upload/image",
                acceptMime: "image/gif,image/jpeg,image/jpg,image/png",
                done: function (res) {
                    coverImage = res.data.url
                    data.cover_bg = res.data.url
                    editArea()
                }
            });

            layui.upload.render({
                elem: "#marker",
                url: "/app/admin/upload/image",
                acceptMime: "image/gif,image/jpeg,image/jpg,image/png",
                done: function (res) {
                    data.marker_icon = res.data.url
                    editArea(true)
                }
            });

            let edit2 = function(obj) {
                let value = obj.data[PRIMARY_KEY];
                layer.open({
                    type: 2,
                    title: "修改",
                    shade: 0.1,
                    shadeClose:true,
                    area: ["500px", "450px"],
                    content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
                });
            }

            let editArea = function(refresh) {
                layui.$.ajax({
                    url: "/app/admin/scenic-area/update",
                    type: "POST",
                    dateType: "json",
                    data: data,
                    success: function (res) {
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        initCoverImage()

                        if (refresh) {
                            return layui.popup.success("操作成功", refreshTable);
                        }
                        return layui.popup.success("操作成功");
                    }
                });
            }

            let add = function(position) {
                layer.open({
                    type: 2,
                    title: "新增景点",
                    shade: 0.1,
                    shadeClose:true,
                    area: ["500px", "450px"],
                    content: INSERT_URL + '?lng=' + position.lng + '&lat=' + position.lat
                });
            }
            
            // 表格渲染
            layui.use(["table", "form", "common", "popup", "util"], function() {
                let table = layui.table;
                let form = layui.form;
                let $ = layui.$;
                let common = layui.common;
                let util = layui.util;
                
				// 表头参数
				let cols = [
					{
						type: "checkbox",
						align: "center"
					},{
						title: "id",align: "center",
						field: "id",
					},{
						title: "景点名称",align: "center",
						field: "name",
					},{
						title: "操作",
						toolbar: "#table-bar",
						align: "center",
						fixed: "right",
						width: 120,
					}
				];
				
				// 渲染表格
				table.render({
				    elem: "#data-table",
				    url: SELECT_API,
				    page: true,
				    cols: [cols],
				    skin: "line",
				    size: "lg",
				    toolbar: "#table-toolbar",
				    autoSort: false,
				    defaultToolbar: [{
				        title: "刷新",
				        layEvent: "refresh",
				        icon: "layui-icon-refresh",
				    }, "filter", "print", "exports"],
				    done: function () {
				        layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
				    }
				});
				
				
                // 编辑或删除行事件
                table.on("tool(data-table)", function(obj) {
                    if (obj.event === "remove") {
                        remove(obj);
                    } else if (obj.event === "edit") {
                        edit(obj);
                    }
                });

                // 表格顶部工具栏事件
                table.on("toolbar(data-table)", function(obj) {
                    if (obj.event === "add") {
                        add();
                    } else if (obj.event === "refresh") {
                        refreshTable();
                    } else if (obj.event === "batchRemove") {
                        batchRemove(obj);
                    }
                });

                // 表格顶部搜索事件
                form.on("submit(table-query)", function(data) {
                    table.reload("data-table", {
                        page: {
                            curr: 1
                        },
                        where: data.field
                    })
                    return false;
                });
                
                // 表格顶部搜索重置事件
                form.on("submit(table-reset)", function(data) {
                    table.reload("data-table", {
                        where: []
                    })
                });
                
                // 字段允许为空
                form.verify({
                    phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
                    email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
                    url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
                    number: [/(^$)|^\d+$/,'只能填写数字'],
                    date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
                    identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
                });

                // 表格排序事件
                table.on("sort(data-table)", function(obj){
                    table.reload("data-table", {
                        initSort: obj,
                        scrollPos: "fixed",
                        where: {
                            field: obj.field,
                            order: obj.type
                        }
                    });
                });

                // 表格新增数据


                // 表格编辑数据
                let edit = function(obj) {
                    let value = obj.data[PRIMARY_KEY];
                    layer.open({
                        type: 2,
                        title: "修改",
                        shade: 0.1,
                        shadeClose:true,
                        area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
                        content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
                    });
                }

                // 删除一行
                let remove = function(obj) {
                    return doRemove(obj.data[PRIMARY_KEY]);
                }

                // 删除多行
                let batchRemove = function(obj) {
                    let checkIds = common.checkField(obj, PRIMARY_KEY);
                    if (checkIds === "") {
                        layui.popup.warning("未选中数据");
                        return false;
                    }
                    doRemove(checkIds.split(","));
                }

                // 执行删除
                let doRemove = function (ids) {
                    let data = {};
                    data[PRIMARY_KEY] = ids;
                    layer.confirm("确定删除?", {
                        icon: 3,
                        title: "提示"
                    }, function(index) {
                        layer.close(index);
                        let loading = layer.load();
                        $.ajax({
                            url: DELETE_API,
                            data: data,
                            dataType: "json",
                            type: "post",
                            success: function(res) {
                                layer.close(loading);
                                if (res.code) {
                                    return layui.popup.failure(res.msg);
                                }
                                return layui.popup.success("操作成功", refreshTable);
                            }
                        })
                    });
                }

                // 刷新表格数据
                window.refreshTable = function(param) {
                    window.location.reload()
                }
            })

        </script>
    </body>
</html>
